package com.yami.shop.api.controller;

import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.security.common.manager.TokenStore;
import com.yami.shop.security.common.vo.TokenInfoVO;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wxapi")
@Tag(name = "微信接口")
@AllArgsConstructor
public class WXController {

    private final Logger logger = LoggerFactory.getLogger(WXController.class);

    //需要打开com.yami.shop.api.config.WxMaConfiguration 配置后使用
    //private final WxMaService wxMaService;

    private final UserService userService;

    private final TokenStore tokenStore;



    private final PasswordEncoder passwordEncoder;

    private static final String wxMinAppId = "wxba79fb0f578f6ef9";


    /*
     * 微信登录获取openid
     */
    @Operation(summary = "微信登录wxinit" , description = "微信登录wxinit")
    @Parameters({
            @Parameter(name = "openId", description = "微信openId" , required = false)
    })
    @RequestMapping(value="/wxinit",method= RequestMethod.GET)
    public ResponseEntity<String> wxinit(@RequestParam(value="openId",required=false) String openId) {

       /* try {
            WXLoginDto wxLoginDto = new WXLoginDto();
            String tempToken = TokenGenerator.generateValue();
            wxLoginDto.setSessionKey(tempToken);
            if(null!=openId && !"".equals(openId)){
                User one = userService.getOne(new LambdaQueryWrapper<User>()
                        .select(User::getUserId,User::getOpenId,User::getUnionid,User::getUserMobile,User::getStatus,User::getInviteCode,User::getUserType,User::getBehalfType)
                        .eq(User::getOpenId, openId));
                UserBaseDto userDto = mapperFacade.map(one, UserBaseDto.class);
                wxLoginDto.setUsers(userDto);
                if(null!=one && null!=one.getOpenId() && !"".equals(one.getOpenId())){
                    wxLoginDto.setOpenId(one.getOpenId());
                    wxLoginDto.setUnionid(one.getUnionid());
                    wxLoginDto.setPhoneNumber(null != one.getUserMobile()?one.getUserMobile():"");
                    wxLoginDto.setStatus(one.getStatus());
                    wxLoginDto.setUserId(one.getUserId());
                    wxLoginDto.setInviteCode(one.getInviteCode());
                }
            }
            wxinitTmepToken.put(tempToken,wxLoginDto);
            return ResponseEntity.ok(wxLoginDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }*/
        return ResponseEntity.ok().build();
    }

    /*
     * 微信登录获取openid
     */
    @Operation(summary = "微信登录" , description = "微信登录获取openid")
    @Parameters({
            @Parameter(name = "code", description = "微信code" , required = true),
            @Parameter(name = "pid", description = "邀请码" , required = false),
            @Parameter(name = "temptoken", description = "临时token" , required = false),
    })
    @RequestMapping(value="/wxlogin",method= RequestMethod.GET)
    public ResponseEntity<String> wxlogin(@RequestParam(value="code",required=true) @NotNull(message="微信code") String code,
                                              @RequestParam(value="pid",required=false) String pid,
                                              @RequestParam(value="temptoken",required=false) String temptoken) {
        if (StringUtils.isBlank(code)) {
            throw new YamiShopBindException("empty jscode");
        }
        /*if (!wxMaService.switchover(wxMinAppId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", wxMinAppId));
        }*/
        try {
           /* WXLoginDto tempTokenInfo = wxinitTmepToken.get(temptoken,true);
            if(null== tempTokenInfo || null==tempTokenInfo.getOpenId()){
                WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
                WXLoginDto wxLoginDto = new WXLoginDto();
                wxLoginDto.setOpenId(session.getOpenid());
                wxLoginDto.setUnionid(session.getUnionid());
                if(null!=session.getOpenid() && !"".equals(session.getOpenid())){
                    String loginPwd = passwordEncoder.encode("zkyx123456");
                    User user = userService.wxLogin(wxLoginDto, pid, loginPwd);
                    UserBaseDto userDto = mapperFacade.map(user, UserBaseDto.class);
                    wxLoginDto.setUsers(userDto);
                    wxLoginDto.setInviteCode(user.getInviteCode());
                    if(user.getUserMobile() != null && !"".equals(user.getUserMobile())) {
                        tempTokenInfo.setOpenId(user.getOpenId());
                        tempTokenInfo.setUnionid(user.getUnionid());
                        tempTokenInfo.setPhoneNumber(null != user.getUserMobile() ? user.getUserMobile() : "");
                        tempTokenInfo.setStatus(user.getStatus());
                        tempTokenInfo.setUserId(user.getUserId());
                        tempTokenInfo.setUsers(userDto);
                        return ResponseEntity.ok(uTokenCacheFun(tempTokenInfo, session, code));
                    }
                    return ResponseEntity.ok(wxLoginDto);
                }
            }
            if(tempTokenInfo.getPhoneNumber() != null && !"".equals(tempTokenInfo.getPhoneNumber())){
                return ResponseEntity.ok(uTokenCacheFun(tempTokenInfo,null, code));
            }
            return ResponseEntity.ok(tempTokenInfo);*/
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return ResponseEntity.ok().build();
    }


   /* private WXLoginDto uTokenCacheFun(WXLoginDto tempTokenInfo,WxMaJscode2SessionResult session,String wxCode) throws WxErrorException {
        //WXLoginDto uTokenDtoCache = uTokenCache.get(tempTokenInfo.getUserId(), false);
        WXLoginDto uTokenDtoCache  = (WXLoginDto) RedisUtil.get("utoken:".concat(tempTokenInfo.getUserId()));

        if(null!=uTokenDtoCache && null!=uTokenDtoCache.getUToken() && !"".equals(uTokenDtoCache.getUToken().getAccessToken())){
            if(!tokenStore.exitsUserInfoByAccessToken(uTokenDtoCache.getUToken().getAccessToken(), true)){
                uTokenDtoCache = null;
            }
        }

        UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();

        userInfoInToken.setUserId(tempTokenInfo.getUserId());
        userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value());
        userInfoInToken.setEnabled(tempTokenInfo.getStatus() == 1);
        if(uTokenDtoCache == null){
            if(session == null){
                session = wxMaService.getUserService().getSessionInfo(wxCode);
            }
            if(session.getSessionKey() != null && !"".equals(session.getSessionKey())){

                // 存储token返回vo
                TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken);
                UserTokenDto userTokenDto = new UserTokenDto();
                userTokenDto.setAccessToken(tokenInfoVO.getAccessToken());
                userTokenDto.setRefreshToken(tokenInfoVO.getRefreshToken());
                userTokenDto.setExpiresIn(tokenInfoVO.getExpiresIn());
                tempTokenInfo.setUToken(userTokenDto);

                //uTokenCache.put(tempTokenInfo.getUserId(),tempTokenInfo);
                RedisUtil.set("utoken:".concat(tempTokenInfo.getUserId()),tempTokenInfo,DateUnit.HOUR.getMillis()*36);
                return tempTokenInfo;
            }else{
                throw  new YamiShopBindException("非法登录");
            }

        }
        return uTokenDtoCache;
    }*/

    /*
     * 获取微信手机号
     */
    @Operation(summary = "微信手机号登录绑定" , description = "微信手机号登录绑定")
    @Parameters({
            @Parameter(name = "code", description = "微信code" , required = true),
            @Parameter(name = "openId", description = "微信openid" , required = false)
    })
    @RequestMapping(value="/wxPhoneLogin",method= RequestMethod.GET)
    public ResponseEntity<TokenInfoVO> getPhoneNumber(@RequestParam(value="code",required=true) @NotNull(message="微信code") String code,
                                                     @RequestParam(value="openId",required=true) @NotNull(message="微信openId") String openId) {
        if (StringUtils.isBlank(code)) {
            throw new YamiShopBindException("empty jscode");
        }
        /*if (!wxMaService.switchover(wxMinAppId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", wxMinAppId));
        }*/
        try {
           /* WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
            WxMaConfigHolder.remove();//清理ThreadLocal
            if(null!=phoneNoInfo && null!=phoneNoInfo.getPhoneNumber() && !"".equals(phoneNoInfo.getPhoneNumber())){
                WXLoginDto wxLoginDto = new WXLoginDto();
                wxLoginDto.setPhoneNumber(phoneNoInfo.getPhoneNumber());
                wxLoginDto.setOpenId(openId);
                User tzUser = userService.wxRegisterLogin(wxLoginDto);
                if(null==tzUser){
                    String loginPwd = passwordEncoder.encode("zkyx123456");
                    tzUser = userService.wxLogin(wxLoginDto,"AAAA",loginPwd);
                }
                UserInfoInTokenBO userInfoInToken = new UserInfoInTokenBO();
                userInfoInToken.setUserId(tzUser.getUserId());
                userInfoInToken.setSysType(SysTypeEnum.ORDINARY.value());
                userInfoInToken.setEnabled(tzUser.getStatus() == 1);
                // 存储token返回vo
                TokenInfoVO tokenInfoVO = tokenStore.storeAndGetVo(userInfoInToken);
                return ResponseEntity.ok(tokenInfoVO);
            }*/
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            throw new YamiShopBindException("授权登录失败");
        }
        return ResponseEntity.ok().build();
    }
}
